//
//  QRCodeViewController.swift
//  LXQWB
//
//  Created by 江海天 on 2017/7/9.
//  Copyright © 2017年 江海天. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {
	///容器视图高度约束
	@IBOutlet weak var tabbar: UITabBar!
	@IBOutlet weak var containerHeightCons: NSLayoutConstraint!
	///冲击波约束
	@IBOutlet weak var scanline: NSLayoutConstraint!
	///容器视图
	@IBOutlet weak var containerView: UIView!
	///我的名片
	@IBOutlet weak var myInfo: UIButton!
	///展示信息
	@IBOutlet weak var titleInfo: UILabel!
	
	//MARK: - 周期方法
    override func viewDidLoad() {
        super.viewDidLoad()
		tabbar.delegate = self
		tabbar.selectedItem = tabbar.items?[0]
		sanQRCode()
		//初始化二维码扫描
		//1输入
		
		
		
        // Do any additional setup after loading the view.
    }
	override func viewWillAppear(_ animated: Bool) {
		super.viewWillAppear(animated)
		sanlineAnimation()
	}
		@IBOutlet weak var dismissView: UIBarButtonItem!
	private func sanlineAnimation(){
		scanline.constant = containerHeightCons.constant
		view.layoutIfNeeded()
		UIView.animate(withDuration: 1, animations: {
			UIView.setAnimationRepeatCount(MAXFLOAT)
			self.scanline.constant = -self.containerHeightCons.constant
			self.view.layoutIfNeeded()
		}, completion: nil)
	}
	
	@IBAction func createInfo(_ sender: Any) {
		let myInfo = InfoViewController()
		self.navigationController?.pushViewController(myInfo, animated: false)
	}
	@IBAction func sanImage(_ sender: Any) {
		let imageVC = UIImagePickerController()
		imageVC.sourceType = UIImagePickerControllerSourceType.photoLibrary
		imageVC.delegate = self
		present(imageVC, animated: true, completion: nil)
	}
	@IBAction func dismissView(_ sender: Any) {
		dismiss(animated: true, completion: nil)
	}
	
	func sanQRCode(){
		//判断能否添加
		if !session.canAddInput(input) {
			return
		}
		if !session.canAddOutput(output) {
			return
		}
		//添加
		session.addInput(input)
		session.addOutput(output)
		
		//需要先加入后设置,解析数据
		NLog(message: output.availableMetadataObjectTypes)
	
		output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
		
		//output.metadataObjectTypes = [AVMetadataObjectTypeEAN8Code]
		
		//output.type
		
		
		//添加代理
		output.setMetadataObjectsDelegate(self, queue:DispatchQueue.main)
		//预览图层
		view.layer.insertSublayer(preLazy, at: 0)
		preLazy.frame = view.bounds
		//开始扫描
		session.startRunning()
	}
    // MARK: - lazy
	lazy var preLazy:AVCaptureVideoPreviewLayer = 	AVCaptureVideoPreviewLayer(session: self.session)
	lazy var input = { () -> AVCaptureDeviceInput? in
		let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
		return try? AVCaptureDeviceInput(device: device)
	}()
	lazy var session = AVCaptureSession()
	
	lazy var output:AVCaptureMetadataOutput = {
		let out = AVCaptureMetadataOutput()
		let viewRect = self.view.frame
		let containRect = self.containerView.frame
		let x = containRect.origin.y/viewRect.height
		let y = containRect.origin.x/viewRect.width
		let width = containRect.height/viewRect.height
		let height = containRect.width/viewRect.width
		out.rectOfInterest = CGRect(x: x, y: y, width: width, height: height)
		return out
	}()
	lazy var Baselayer = CAShapeLayer()
}
extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate{
	func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!)
	{
		Baselayer.removeFromSuperlayer()
		//titleInfo.text = metadataObjects.last as? AnyObject
		guard metadataObjects.last != nil else{
			return
		}
		let object = preLazy.transformedMetadataObject(for: metadataObjects.last as! AVMetadataMachineReadableCodeObject) as! AVMetadataMachineReadableCodeObject
		titleInfo.text = object.stringValue
		
		
		drawLine(object: object)
		NLog(message: object)
	}
	func drawLine(object:AVMetadataMachineReadableCodeObject){
		guard let array = object.corners else {
			return
		}
		
		//创建涂层
		
		let start = CGPoint(dictionaryRepresentation: array[0] as! CFDictionary)
		
		Baselayer.strokeColor = UIColor.yellow.cgColor
		Baselayer.lineWidth = 2
		Baselayer.fillColor = UIColor.clear.cgColor
		let path = UIBezierPath()
		path.move(to: start!)
		for i in 1...3 {
			let point = CGPoint(dictionaryRepresentation: array[i] as! CFDictionary)
			path.addLine(to: point!)

		}
		path.close()
		Baselayer.path = path.cgPath
		view.layer.addSublayer(Baselayer)
	}
}
extension QRCodeViewController:UITabBarDelegate{
	func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem){
		if item.tag == 0 {
			//session.stopRunning()
			UIView.animate(withDuration: 0.5, animations: {
				self.containerHeightCons.constant = 250
			})
			
			//output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
			//session.startRunning()
			
			
			
		}else{
			//session.stopRunning()
			UIView.animate(withDuration: 0.5, animations: { 
				self.containerHeightCons.constant = 150
			})
			
			//output.metadataObjectTypes = [AVMetadataObjectTypeEAN8Code]
			//session.startRunning()
		}
		
		
	}
}
extension QRCodeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
	func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
		guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else{
			return
		}
		
		let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyLow])
		guard let ciImage = image.ciImage else {
			return
		}
		guard let array = detector?.features(in:ciImage ) else{
			//picker.dismiss(animated: true, completion: nil)
			return
		}
		for result in array {
			NLog(message: (result as? CIQRCodeFeature)?.messageString)
		}
		picker.dismiss(animated: true, completion: nil)
	}

}
